package com.yuchen.advsdk.util;

import android.app.usage.StorageStatsManager;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Locale;
import java.util.UUID;

public class DeviceUtil {
    public static String getDeviceSn() {
        String checkImei = getDeviceImei();
        if (TextUtils.isEmpty(checkImei)){
            String deviceSn = getMac()+"-"+getCpuSerial()+"-starsaiot";
            checkImei = deviceSn;
            saveDeviceImei(checkImei);
        }
//        Log.d("DeviceUtil","当前设备SN-"+deviceSn);
        return checkImei;
    }

    public static String getCpuSerial(){
        Process p =null;
        try{
//            p = Runtime.getRuntime().exec("/system/bin/cat proc/cpuinfo | grep Serial | busybox awk '{print$3}'");
            p = Runtime.getRuntime().exec(new String[]{"/system/bin/sh","-c","cat proc/cpuinfo | grep Serial | busybox awk '{print$3}' \n"});
            BufferedReader buf =new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str =new String();
            String pingResult = new String();

            while((str=buf.readLine())!=null){
                pingResult = str;
            }
            buf.close();
            return pingResult.trim();
        }catch (Exception e){
//            throw new RuntimeException("getCpuSerial fail "+e.getMessage());
            return "default_cpu";
        }
    }

    public static String getDeviceImei(){
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/yuchen/imei");
        if (!file.exists()){
            return null;
        }
        String imei = FileUtil.readFile(file.getAbsolutePath());
        return imei;
    }

    public static void saveDeviceImei(String imei){
        if (TextUtils.isEmpty(imei)){
            imei = UUID.randomUUID().toString().replaceAll("-","")+"-starsaiot";
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/yuchen/imei");
        if (!file.exists()){
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos =null;
        try {
            fos = new FileOutputStream(file);
            fos.write(imei.getBytes());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }finally {
                    fos = null;
                }
            }
        }
    }

    public static String getMac() {
        try{
            StringBuffer fileData = new StringBuffer(1024);
            BufferedReader reader = new BufferedReader(new FileReader("/sys/class/net/eth0/address"));
            char[] buf = new char[1024];
            int numRead = 0;

            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
            }
            reader.close();
            return fileData.toString().substring(0, 17);
        }catch (Exception e){
//            throw new RuntimeException("getMac fail "+e.getMessage());
            return "default_mac";
        }


    }


    // 获得可用的内存
//    public static String getMemoryAvail(Context mContext) {
//        if (mContext == null) {
//            return "unknow";
//        }
//        // 得到ActivityManager
//        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
//        // 创建ActivityManager.MemoryInfo对象
//
//        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
//        am.getMemoryInfo(mi);
//
//        // 取得剩余的内存空间
//        return getUnit(Float.valueOf(mi.availMem));
//    }

    // 获得总内存
//    public static String getMemoryAll() {
//        long mTotal;
//        // /proc/meminfo读出的内核信息进行解释
//        String path = "/proc/meminfo";
//        String content = null;
//        BufferedReader br = null;
//        try {
//            br = new BufferedReader(new FileReader(path), 8);
//            String line;
//            if ((line = br.readLine()) != null) {
//                content = line;
//            }
//            // beginIndex
//            int begin = content.indexOf(':');
//            // endIndex
//            int end = content.indexOf('k');
//            // 截取字符串信息
//
//            content = content.substring(begin + 1, end).trim();
//            mTotal = Integer.parseInt(content) * 1024;
//        } catch (Exception e) {
//            e.printStackTrace();
//            mTotal = 0;
//        } finally {
//            if (br != null) {
//                try {
//                    br.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return getUnit(mTotal);
//    }

    public static String getStorageAll() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());

//        //存储块总数量
//        long blockCount = statFs.getBlockCountLong();
//        //块大小
//        long blockSize = statFs.getBlockSizeLong();
//        //可用块数量
//        long availableCount = statFs.getAvailableBlocksLong();
//        //剩余块数量，注：这个包含保留块（including reserved blocks）即应用无法使用的空间
//        long freeBlocks = statFs.getFreeBlocksLong();
        //这两个方法是直接输出总内存和可用空间，也有getFreeBytes
        //API level 18（JELLY_BEAN_MR2）引入
        long totalSize = statFs.getTotalBytes();
//        long availableSize = statFs.getAvailableBytes();
        return getUnit(totalSize);
    }



    /**
     * API 26 android O
     * 获取总共容量大小，包括系统大小
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static long getTotalSize(Context context, String fsUuid) {
        try {
            UUID id;
            if (fsUuid == null) {
                id = StorageManager.UUID_DEFAULT;
            } else {
                id = UUID.fromString(fsUuid);
            }
            StorageStatsManager stats = context.getSystemService(StorageStatsManager.class);
            return stats.getTotalBytes(id);
        } catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static String getStorageAvail() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long availableSize = statFs.getAvailableBytes();
        return getUnit(availableSize);
    }

    public static int getStorageAvailAlarm() {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long availableSize = statFs.getAvailableBytes();
        if(availableSize < 1073741824){
            return -1;
        }
        return 0;
    }



    private static String[] units = {"B", "KB", "MB", "GB", "TB"};

    /**
     * 单位转换
     */
    private static String getUnit(float size) {
        int index = 0;
        while (size > 1024 && index < 4) {
            size = size / 1024;
            index++;
        }
        return String.format(Locale.getDefault(), "%.2f%s", size, units[index]);
    }

    public static int getVolume(Context context){
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
        int current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );
        return (int)((Float.valueOf(current)/max)*100);
    }

    public static int setVolume(Context context, int volume){
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
        int current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );
        int volumeInt = (int)(Float.valueOf(volume)/100*max);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeInt, AudioManager.FLAG_SHOW_UI);
        return volumeInt;
    }

    /**
     *  "总计:" + getAndroidCpuMemInfo(1) + "\n可用:" + getAndroidCpuMemInfo(2)
     * @param val 1.总计   2 可用
     * @return
     */
    public static String getAndroidCpuMemInfo(int val) {
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec(new String[]{"/system/bin/sh", "-c", "cat /proc/meminfo | busybox awk '{print $2}' | busybox sed -n '" + val + "p' \n"});
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    str = str.trim();// 去空格
                    str = getUnit(Float.parseFloat(str) * 1024);
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return str;
    }
}
